<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - 物流订单管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <!-- 引入主题CSS -->
    <link rel="stylesheet" href="/css/theme.css">
    <style>
        .container-main {
            margin-top: 20px;
            background-color: var(--card-bg);
            padding: 30px;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
        }
        
        .section-title {
            font-size: 1.75rem;
            font-weight: 500;
            margin-bottom: 25px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
        }
        
        .profile-card {
            background-color: var(--card-bg);
            border-radius: var(--border-radius);
            box-shadow: var(--card-shadow);
            padding: 20px;
            margin-bottom: 20px;
            transition: transform var(--transition-speed), box-shadow var(--transition-speed);
        }
        
        .profile-card:hover {
            box-shadow: var(--box-shadow);
        }
        
        .avatar-container {
            width: 120px;
            height: 120px;
            margin: 0 auto 20px;
            border-radius: 50%;
            overflow: hidden;
            background-color: var(--primary-light);
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .avatar-container i {
            font-size: 60px;
            color: var(--primary-color);
        }
        
        .order-item {
            border-left: 4px solid var(--primary-color);
            padding-left: 15px;
            margin-bottom: 15px;
        }
        
        .status-badge {
            font-size: 0.8rem;
            padding: 0.25rem 0.5rem;
        }
        
        .tab-content {
            padding-top: 20px;
        }
        
        .nav-tabs .nav-link {
            color: var(--text-primary);
            border: none;
            border-bottom: 3px solid transparent;
            padding: 10px 20px;
        }
        
        .nav-tabs .nav-link.active {
            color: var(--primary-color);
            background-color: transparent;
            border-bottom: 3px solid var(--primary-color);
        }
        
        .nav-tabs .nav-link:hover {
            border-color: transparent;
            border-bottom: 3px solid var(--primary-light);
        }
    </style>
</head>
<body>

<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg navbar-dark bg-primary sticky-top">
    <div class="container-fluid">
        <a class="navbar-brand" href="/"><i class="bi bi-truck me-2"></i>物流订单管理系统</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto"> <!-- 添加me-auto使导航项靠左 -->
                <!-- 主导航项 -->
                <li class="nav-item">
                    <a class="nav-link" href="/"><i class="bi bi-clipboard-check me-1"></i>订单处理</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="/profile.html"><i class="bi bi-person me-1"></i>个人中心</a>
                </li>
            </ul>
            
            <ul class="navbar-nav ms-auto">
                <!-- 订单创建按钮 -->
                <li class="nav-item me-2">
                    <a class="btn btn-success" href="/">
                        <i class="bi bi-plus-circle-fill me-1"></i> 创建新订单
                    </a>
                </li>

                <!-- 用户认证相关链接 -->
                <li class="nav-item" id="authLinksContainer">
                    <a class="btn btn-primary" href="/login.html">登录</a>
                </li>
                <li class="nav-item dropdown" id="userDropdownContainer" style="display: none;">
                    <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-person-circle me-1"></i> <span id="usernameDisplay">用户</span>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                        <li><a class="dropdown-item" href="/profile.html"><i class="bi bi-person me-2"></i>个人中心</a></li>
                        <li><a class="dropdown-item" href="#" id="logoutButton"><i class="bi bi-box-arrow-right me-2"></i>登出</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div class="container container-main">
    <h2 class="section-title"><i class="bi bi-person-circle me-2"></i>个人中心</h2>
    
    <div class="row">
        <!-- 左侧个人信息 -->
        <div class="col-md-4 mb-4">
            <div class="profile-card text-center">
                <!-- 添加欢迎信息 -->
                <div class="alert alert-success mb-3" role="alert">
                    <i class="bi bi-emoji-smile me-2"></i>
                    <span id="profileWelcomeText">欢迎回来！</span>
                </div>
                <div class="avatar-container">
                    <i class="bi bi-person"></i>
                </div>
                <h3 id="profileUsername">加载中...</h3>
                <p class="text-muted" id="profileRoles">加载中...</p>
                <hr>
                <div class="d-grid gap-2">
                    <button class="btn btn-outline-primary" id="changePasswordBtn">
                        <i class="bi bi-key me-1"></i> 修改密码
                    </button>
                    <button class="btn btn-outline-success" id="manageEmailBtn">
                        <i class="bi bi-envelope me-1"></i> 邮箱管理
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 右侧订单信息 -->
        <div class="col-md-8">
            <div class="card">
                <div class="card-header bg-white">
                    <ul class="nav nav-tabs card-header-tabs" id="orderTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="all-orders-tab" data-bs-toggle="tab" data-bs-target="#all-orders" type="button" role="tab" aria-controls="all-orders" aria-selected="true">
                                <i class="bi bi-list-ul me-1"></i> 全部订单
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="pending-orders-tab" data-bs-toggle="tab" data-bs-target="#pending-orders" type="button" role="tab" aria-controls="pending-orders" aria-selected="false">
                                <i class="bi bi-hourglass-split me-1"></i> 待处理
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="completed-orders-tab" data-bs-toggle="tab" data-bs-target="#completed-orders" type="button" role="tab" aria-controls="completed-orders" aria-selected="false">
                                <i class="bi bi-check-circle me-1"></i> 已完成
                            </button>
                        </li>
                    </ul>
                </div>
                <div class="card-body">
                    <div class="tab-content" id="orderTabsContent">
                        <!-- 全部订单 -->
                        <div class="tab-pane fade show active" id="all-orders" role="tabpanel" aria-labelledby="all-orders-tab">
                            <div id="allOrdersList" class="orders-container">
                                <div class="text-center py-5">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                    <p class="mt-2">加载订单中...</p>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 待处理订单 -->
                        <div class="tab-pane fade" id="pending-orders" role="tabpanel" aria-labelledby="pending-orders-tab">
                            <div id="pendingOrdersList" class="orders-container">
                                <!-- 待处理订单将通过JS动态加载 -->
                            </div>
                        </div>
                        
                        <!-- 已完成订单 -->
                        <div class="tab-pane fade" id="completed-orders" role="tabpanel" aria-labelledby="completed-orders-tab">
                            <div id="completedOrdersList" class="orders-container">
                                <!-- 已完成订单将通过JS动态加载 -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 修改密码模态框 -->
<div class="modal fade" id="changePasswordModal" tabindex="-1" aria-labelledby="changePasswordModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="changePasswordModalLabel"><i class="bi bi-key me-2"></i>修改密码</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="changePasswordForm">
                    <div class="mb-3">
                        <label for="currentPassword" class="form-label">当前密码</label>
                        <input type="password" class="form-control" id="currentPassword" required>
                    </div>
                    <div class="mb-3">
                        <label for="newPassword" class="form-label">新密码</label>
                        <input type="password" class="form-control" id="newPassword" required minlength="6">
                    </div>
                    <div class="mb-3">
                        <label for="confirmNewPassword" class="form-label">确认新密码</label>
                        <input type="password" class="form-control" id="confirmNewPassword" required minlength="6">
                    </div>
                </form>
                <div id="passwordChangeAlert" class="alert" style="display: none;"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="savePasswordBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 邮箱管理模态框 -->
<div class="modal fade" id="emailManagementModal" tabindex="-1" aria-labelledby="emailManagementModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="emailManagementModalLabel">
                    <i class="bi bi-envelope me-2"></i>邮箱管理
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-4">
                    <h6><i class="bi bi-envelope-plus me-1"></i>添加邮箱地址</h6>
                    <form id="addEmailForm">
                        <div class="mb-3">
                            <label for="newEmailAddress" class="form-label">邮箱地址</label>
                            <input type="email" class="form-control" id="newEmailAddress" placeholder="example@email.com" required>
                        </div>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="newEmailNotificationEnabled" checked>
                            <label class="form-check-label" for="newEmailNotificationEnabled">
                                启用邮件通知
                            </label>
                        </div>
                        <button type="submit" class="btn btn-primary btn-sm">
                            <i class="bi bi-plus-circle me-1"></i>添加邮箱
                        </button>
                    </form>
                </div>
                
                <div class="mb-3">
                    <h6><i class="bi bi-list-ul me-1"></i>已保存的邮箱地址</h6>
                    <div id="emailList" class="list-group">
                        <div class="text-center py-3">
                            <div class="spinner-border spinner-border-sm text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2 mb-0 text-muted">加载邮箱列表中...</p>
                        </div>
                    </div>
                </div>
                
                <div id="emailManagementAlert" class="alert" style="display: none;"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // DOM 元素
    const profileUsername = document.getElementById('profileUsername');
    const profileRoles = document.getElementById('profileRoles');
    const allOrdersList = document.getElementById('allOrdersList');
    const pendingOrdersList = document.getElementById('pendingOrdersList');
    const completedOrdersList = document.getElementById('completedOrdersList');
    const changePasswordBtn = document.getElementById('changePasswordBtn');
    const changePasswordModal = new bootstrap.Modal(document.getElementById('changePasswordModal'));
    const changePasswordForm = document.getElementById('changePasswordForm');
    const savePasswordBtn = document.getElementById('savePasswordBtn');
    const passwordChangeAlert = document.getElementById('passwordChangeAlert');
    
    // 邮箱管理相关元素
    const manageEmailBtn = document.getElementById('manageEmailBtn');
    const emailManagementModal = new bootstrap.Modal(document.getElementById('emailManagementModal'));
    const addEmailForm = document.getElementById('addEmailForm');
    const emailList = document.getElementById('emailList');
    const emailManagementAlert = document.getElementById('emailManagementAlert');
    const authLinksContainer = document.getElementById('authLinksContainer');
    const userDropdownContainer = document.getElementById('userDropdownContainer');
    const usernameDisplay = document.getElementById('usernameDisplay');
    const logoutButton = document.getElementById('logoutButton');

    const API_BASE_URL = '/api/v1';

    // 页面加载时检查登录状态
    document.addEventListener('DOMContentLoaded', () => {
        checkLoginStatusAndUpdateUI();
        loadUserOrders();
        
        // 绑定事件监听器
        changePasswordBtn.addEventListener('click', () => {
            changePasswordForm.reset();
            passwordChangeAlert.style.display = 'none';
            changePasswordModal.show();
        });
        
        savePasswordBtn.addEventListener('click', handleChangePassword);
        
        // 邮箱管理事件监听器
        manageEmailBtn.addEventListener('click', () => {
            emailManagementAlert.style.display = 'none';
            loadUserEmails();
            emailManagementModal.show();
        });
        
        addEmailForm.addEventListener('submit', handleAddEmail);
        
        if (logoutButton) {
            logoutButton.addEventListener('click', handleLogout);
        }
    });

    // 检查登录状态并更新UI
    async function checkLoginStatusAndUpdateUI() {
        try {
            const response = await fetch(`${API_BASE_URL}/orders/me`);
            if (response.ok) {
                const user = await response.json();
                console.log('User logged in:', user);
                
                // 检查用户是否为配送员角色
                if (user.roles && Array.isArray(user.roles)) {
                    for (let i = 0; i < user.roles.length; i++) {
                        const role = user.roles[i];
                        if (role.authority === 'ROLE_DELIVERY_PERSON') {
                            console.log('配送员角色检测到，正在重定向到配送员界面...');
                            window.location.href = '/delivery.html';
                            return; // 重定向后不继续执行
                        }
                    }
                }
                
                // 普通用户界面显示逻辑
                displayLoggedInUI(user);
                updateProfileInfo(user);
            } else if (response.status === 401) {
                console.log('User not logged in (401).');
                displayLoggedOutUI();
                window.location.href = '/login.html'; // 未登录用户重定向到登录页面
            } else {
                console.warn('Error checking login status, server responded with:', response.status);
                displayLoggedOutUI();
            }
        } catch (error) {
            console.error('Network error or other issue checking login status:', error);
            displayLoggedOutUI();
        }
    }

    // 显示已登录UI
    function displayLoggedInUI(user) {
        if (authLinksContainer) authLinksContainer.style.display = 'none';
        if (userDropdownContainer) userDropdownContainer.style.display = 'block';
        if (usernameDisplay) usernameDisplay.textContent = user.username;
    }

    // 显示未登录UI
    function displayLoggedOutUI() {
        if (authLinksContainer) authLinksContainer.style.display = 'block';
        if (userDropdownContainer) userDropdownContainer.style.display = 'none';
    }

    // 更新个人资料信息
    function updateProfileInfo(user) {
        profileUsername.textContent = user.username;
        
        // 添加个性化欢迎信息
        const profileWelcomeText = document.getElementById('profileWelcomeText');
        if (profileWelcomeText) {
            // 根据时间生成不同的欢迎语
            const hour = new Date().getHours();
            let greeting = '';
            
            if (hour < 6) {
                greeting = '夜深了，';
            } else if (hour < 9) {
                greeting = '早上好，';
            } else if (hour < 12) {
                greeting = '上午好，';
            } else if (hour < 14) {
                greeting = '中午好，';
            } else if (hour < 18) {
                greeting = '下午好，';
            } else if (hour < 22) {
                greeting = '晚上好，';
            } else {
                greeting = '夜深了，';
            }
            
            profileWelcomeText.textContent = `${greeting}${user.username}！欢迎来到您的个人中心`;
        }
        
        // 格式化角色显示
        if (user.roles && Array.isArray(user.roles)) {
            const roleNames = [];
            user.roles.forEach(role => {
                let roleName = role;
                if (typeof role === 'object' && role.authority) {
                    roleName = role.authority;
                }
                
                // 转换角色名称为中文
                switch(roleName) {
                    case 'ROLE_USER':
                        roleNames.push('普通用户');
                        break;
                    case 'ROLE_ADMIN':
                        roleNames.push('管理员');
                        break;
                    case 'ROLE_OPERATOR':
                        roleNames.push('操作员');
                        break;
                    case 'ROLE_DELIVERY_PERSON':
                        roleNames.push('配送员');
                        break;
                    default:
                        roleNames.push(roleName.replace('ROLE_', ''));
                }
            });
            profileRoles.textContent = roleNames.join(', ');
        } else {
            profileRoles.textContent = '普通用户';
        }
    }

    // 加载用户订单
    async function loadUserOrders() {
        try {
            // 添加调试信息
            console.log('开始加载用户订单...');
            
            const response = await fetch(`${API_BASE_URL}/orders/user`);
            console.log('订单API响应状态:', response.status);
            
            if (response.ok) {
                const orders = await response.json();
                console.log('获取到的订单数据:', orders);
                displayOrders(orders);
            } else if (response.status === 401) {
                // 未授权，可能需要重新登录
                console.error('未授权访问，需要重新登录');
                window.location.href = '/login.html';
            } else {
                // 其他错误
                console.error('加载订单失败，状态码:', response.status);
                showNoOrdersMessage('加载订单失败，请稍后再试');
            }
        } catch (error) {
            console.error('加载订单时发生错误:', error);
            showNoOrdersMessage('加载订单时发生错误');
        }
    }

    // 显示订单列表
    function displayOrders(orders) {
        if (!orders || orders.length === 0) {
            showNoOrdersMessage('暂无订单记录');
            return;
        }
        
        // 清空加载中的提示
        allOrdersList.innerHTML = '';
        pendingOrdersList.innerHTML = '';
        completedOrdersList.innerHTML = '';
        
        // 对订单进行分类
        const pendingOrders = [];
        const completedOrders = [];
        
        orders.forEach(order => {
            // 创建订单元素
            const orderElement = createOrderElement(order);
            
            // 添加到全部订单列表
            allOrdersList.appendChild(orderElement.cloneNode(true));
            
            // 根据状态分类
            if (order.status === 'SIGNED' || order.status === 'COMPLETED' || order.status === 'DELIVERED') {
                completedOrders.push(orderElement.cloneNode(true));
            } else {
                pendingOrders.push(orderElement.cloneNode(true));
            }
        });
        
        // 更新待处理订单列表
        if (pendingOrders.length > 0) {
            pendingOrders.forEach(element => pendingOrdersList.appendChild(element));
        } else {
            pendingOrdersList.innerHTML = '<div class="text-center py-4"><p class="text-muted">暂无待处理订单</p></div>';
        }
        
        // 更新已完成订单列表
        if (completedOrders.length > 0) {
            completedOrders.forEach(element => completedOrdersList.appendChild(element));
        } else {
            completedOrdersList.innerHTML = '<div class="text-center py-4"><p class="text-muted">暂无已完成订单</p></div>';
        }
    }

    // 创建订单元素
    function createOrderElement(order) {
        const orderDiv = document.createElement('div');
        orderDiv.className = 'order-item p-3 mb-3 bg-light rounded';
        
        // 获取状态中文名称和样式
        const statusInfo = getOrderStatusInfo(order.status);
        
        orderDiv.innerHTML = `
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <h5 class="mb-1">
                        <i class="bi bi-box-seam me-1"></i>
                        订单号: ${order.orderNumber}
                    </h5>
                    <p class="mb-1">
                        <i class="bi bi-geo-alt me-1"></i>
                        从 <strong>${order.shipperInfo.city}</strong> 到 <strong>${order.recipientInfo.city}</strong>
                    </p>
                    <p class="mb-1">
                        <i class="bi bi-calendar-event me-1"></i>
                        创建时间: ${formatDate(order.creationTime)}
                    </p>
                    <p class="mb-0">
                        <i class="bi bi-info-circle me-1"></i>
                        物品: ${order.itemDescription || '未提供描述'}
                    </p>
                </div>
                <span class="badge ${statusInfo.badgeClass} status-badge">${statusInfo.text}</span>
            </div>
            <hr>
            <div class="d-flex justify-content-end">
                <a href="/?order=${order.orderNumber}" class="btn btn-sm btn-outline-primary">
                    <i class="bi bi-search me-1"></i> 查看详情
                </a>
            </div>
        `;
        
        return orderDiv;
    }

    // 获取订单状态信息
    function getOrderStatusInfo(status) {
        const statusMap = {
            "PENDING_PICKUP": { text: "待揽收", badgeClass: "bg-warning" },
            "IN_TRANSIT": { text: "运输中", badgeClass: "bg-info" },
            "OUT_FOR_DELIVERY": { text: "派送中", badgeClass: "bg-info" },
            "DELIVERED": { text: "已签收", badgeClass: "bg-success" },
            "CANCELLED": { text: "已取消", badgeClass: "bg-danger" },
            "EXCEPTION": { text: "异常件", badgeClass: "bg-danger" },
            "PENDING_COLLECTION": { text: "待揽收", badgeClass: "bg-warning" },
            "COLLECTED": { text: "已揽件", badgeClass: "bg-primary" },
            "TRANSPORTING": { text: "运输中", badgeClass: "bg-info" },
            "SIGNED": { text: "已签收", badgeClass: "bg-success" },
            "COMPLETED": { text: "已完成", badgeClass: "bg-success" },
            "DELIVERY_FAILED": { text: "派送失败", badgeClass: "bg-danger" },
            "PENDING_PAYMENT": { text: "等待付款", badgeClass: "bg-warning" }
        };
        
        return statusMap[status] || { text: status, badgeClass: "bg-secondary" };
    }

    // 显示无订单消息
    function showNoOrdersMessage(message) {
        const noOrdersHtml = `
            <div class="text-center py-5">
                <i class="bi bi-inbox text-muted" style="font-size: 3rem;"></i>
                <p class="mt-3 text-muted">${message}</p>
            </div>
        `;
        
        allOrdersList.innerHTML = noOrdersHtml;
        pendingOrdersList.innerHTML = noOrdersHtml;
        completedOrdersList.innerHTML = noOrdersHtml;
    }

    // 处理修改密码
    async function handleChangePassword() {
        const currentPassword = document.getElementById('currentPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmNewPassword = document.getElementById('confirmNewPassword').value;
        
        // 清除之前的提示
        passwordChangeAlert.style.display = 'none';
        
        // 验证新密码和确认密码是否一致
        if (newPassword !== confirmNewPassword) {
            showPasswordChangeAlert('新密码和确认密码不一致', 'danger');
            return;
        }
        
        try {
            // 这里我们假设后端提供了修改密码的API
            // 如果没有，您需要在后端实现这个API
            const response = await fetch(`${API_BASE_URL}/users/change-password`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    currentPassword,
                    newPassword
                })
            });
            
            if (response.ok) {
                showPasswordChangeAlert('密码修改成功', 'success');
                setTimeout(() => {
                    changePasswordModal.hide();
                }, 2000);
            } else if (response.status === 401) {
                showPasswordChangeAlert('当前密码不正确', 'danger');
            } else if (response.status === 404) {
                showPasswordChangeAlert('该功能尚未实现，请联系管理员', 'warning');
            } else {
                showPasswordChangeAlert('密码修改失败，请稍后再试', 'danger');
            }
        } catch (error) {
            console.error('Error changing password:', error);
            showPasswordChangeAlert('发生错误，请稍后再试', 'danger');
        }
    }

    // 显示密码修改提示
    function showPasswordChangeAlert(message, type) {
        passwordChangeAlert.className = `alert alert-${type}`;
        passwordChangeAlert.textContent = message;
        passwordChangeAlert.style.display = 'block';
    }
    
    // 邮箱管理相关函数
    async function loadUserEmails() {
        try {
            emailList.innerHTML = `
                <div class="text-center py-3">
                    <div class="spinner-border spinner-border-sm text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2 mb-0 text-muted">加载邮箱列表中...</p>
                </div>
            `;
            
            const response = await fetch(`${API_BASE_URL}/addresses/me`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            
            if (response.ok) {
                const addresses = await response.json();
                displayEmailList(addresses);
            } else {
                emailList.innerHTML = '<div class="text-center py-3 text-muted">暂无邮箱地址</div>';
            }
        } catch (error) {
            console.error('Error loading emails:', error);
            emailList.innerHTML = '<div class="text-center py-3 text-danger">加载失败，请稍后再试</div>';
        }
    }
    
    function displayEmailList(addresses) {
        if (!addresses || addresses.length === 0) {
            emailList.innerHTML = '<div class="text-center py-3 text-muted">暂无邮箱地址</div>';
            return;
        }
        
        const emailsWithEmail = addresses.filter(addr => addr.email && addr.email.trim() !== '');
        
        if (emailsWithEmail.length === 0) {
            emailList.innerHTML = '<div class="text-center py-3 text-muted">暂无邮箱地址</div>';
            return;
        }
        
        emailList.innerHTML = emailsWithEmail.map(address => `
            <div class="list-group-item d-flex justify-content-between align-items-center">
                <div>
                    <div class="fw-bold">${address.email}</div>
                    <small class="text-muted">${address.name || '未命名地址'}</small>
                    <div class="mt-1">
                        <span class="badge ${address.emailNotificationEnabled ? 'bg-success' : 'bg-secondary'}">
                            ${address.emailNotificationEnabled ? '通知已启用' : '通知已禁用'}
                        </span>
                    </div>
                </div>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="toggleEmailNotification(${address.id}, ${!address.emailNotificationEnabled})">
                        <i class="bi bi-${address.emailNotificationEnabled ? 'bell-slash' : 'bell'}"></i>
                    </button>
                    <button class="btn btn-outline-danger" onclick="deleteEmail(${address.id})">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        `).join('');
    }
    
    async function handleAddEmail(event) {
        event.preventDefault();
        
        const emailAddress = document.getElementById('newEmailAddress').value.trim();
        const notificationEnabled = document.getElementById('newEmailNotificationEnabled').checked;
        
        if (!emailAddress) {
            showEmailManagementAlert('请输入邮箱地址', 'danger');
            return;
        }
        
        try {
            const response = await fetch(`${API_BASE_URL}/addresses/me`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: "邮箱地址",
                    phone: "000-0000-0000",
                    email: emailAddress,
                    emailNotificationEnabled: notificationEnabled,
                    province: "未指定",
                    city: "未指定",
                    district: "未指定",
                    detailAddress: "邮箱地址"
                })
            });
            
            if (response.ok) {
                showEmailManagementAlert('邮箱地址添加成功', 'success');
                addEmailForm.reset();
                document.getElementById('newEmailNotificationEnabled').checked = true;
                loadUserEmails();
            } else {
                showEmailManagementAlert('添加失败，请稍后再试', 'danger');
            }
        } catch (error) {
            console.error('Error adding email:', error);
            showEmailManagementAlert('发生错误，请稍后再试', 'danger');
        }
    }
    
    async function toggleEmailNotification(addressId, enabled) {
        try {
            const response = await fetch(`${API_BASE_URL}/addresses/me/${addressId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    emailNotificationEnabled: enabled
                })
            });
            
            if (response.ok) {
                showEmailManagementAlert(`邮件通知已${enabled ? '启用' : '禁用'}`, 'success');
                loadUserEmails();
            } else {
                showEmailManagementAlert('操作失败，请稍后再试', 'danger');
            }
        } catch (error) {
            console.error('Error toggling email notification:', error);
            showEmailManagementAlert('发生错误，请稍后再试', 'danger');
        }
    }
    
    async function deleteEmail(addressId) {
        if (!confirm('确定要删除这个邮箱地址吗？')) {
            return;
        }
        
        try {
            const response = await fetchAuthenticatedApi(`${API_BASE_URL}/addresses/me/${addressId}`, {
                method: 'DELETE'
            });
            
            if (response.ok) {
                showEmailManagementAlert('邮箱地址删除成功', 'success');
                loadUserEmails();
            } else {
                showEmailManagementAlert('删除失败，请稍后再试', 'danger');
            }
        } catch (error) {
            console.error('Error deleting email:', error);
            if (error.message !== 'Unauthorized' && error.message !== 'Forbidden') {
                showEmailManagementAlert('发生错误，请稍后再试', 'danger');
            }
        }
    }
    
    function showEmailManagementAlert(message, type) {
        emailManagementAlert.className = `alert alert-${type}`;
        emailManagementAlert.textContent = message;
        emailManagementAlert.style.display = 'block';
        
        setTimeout(() => {
            emailManagementAlert.style.display = 'none';
        }, 3000);
    }

    // 处理登出
    function handleLogout(event) {
        if(event) event.preventDefault();
        console.log('Attempting to logout...');
        window.location.href = '/logout'; // 重定向到Spring Security登出端点
    }

    // 格式化日期
    function formatDate(dateString) {
        if (!dateString) return 'N/A';
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return dateString; // 如果无效则返回原始字符串
        return date.toLocaleString('zh-CN', {
            year: 'numeric', month: '2-digit', day: '2-digit',
            hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
        });
    }
</script>
</body>
</html>